package com.xzkydz.all_sensor.socket;
import android.util.Log;
import com.xzkydz.all_sensor.MyApp;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * <p>
 * 基于socket通讯-服务端
 */
public class Server {

    private static ServerSocket SERVER_SOCKET = null;;
    private MyApp myApp;

    public Server(MyApp myApp) {
        this.myApp = myApp;
    }

    static{
        try {
            SERVER_SOCKET = new ServerSocket(8000);
            GetIpAddress.getLocalIpAddress(SERVER_SOCKET);
        } catch (IOException e) {
            Log.d("asd", "\n端口已被占用");
            e.printStackTrace();
        }
    }

    public void start(){
        try {
            Log.d("asd", "IP:" + GetIpAddress.getIP() + " PORT: " + GetIpAddress.getPort());
            Log.d("asd", "-----服务器已启动，等待客户端连接----");
            myApp.setIpStr(GetIpAddress.getIP());
            Socket socket = null;
            while(true){
                //循环监听客户端的连接
                socket = SERVER_SOCKET.accept();
                //新建一个线程ServerSocket，并开启
                new ServerSocketThread(socket,myApp).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
